package com.zhangmeng.tools.controller;

import com.zhangmeng.tools.server.SimpleFtpServer;
import com.zhangmeng.tools.utils.AlertUtils;
import com.zhangmeng.tools.utils.ImagePath;
import javafx.beans.property.SimpleObjectProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.geometry.Pos;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Paint;
import javafx.scene.text.Text;
import javafx.stage.DirectoryChooser;
import javafx.stage.Stage;
import javafx.util.Callback;
import lombok.extern.slf4j.Slf4j;
import org.apache.ftpserver.ftplet.Authority;
import org.apache.ftpserver.usermanager.impl.BaseUser;
import org.apache.ftpserver.usermanager.impl.WritePermission;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * @author : 芊芊墨客
 * @version : 1.0
 * @date : 2023-03-10 11:35
 */
@Slf4j
public class FtpServerController {

    public enum Status{
        init("未启动"),
        start("已启动"),
        stop("已停止"),
        ;

        private String desc;

        Status(String desc) {
            this.desc = desc;
        }

        public String getDesc() {
            return desc;
        }

        public void setDesc(String desc) {
            this.desc = desc;
        }
    }

    @FXML
    public Button server_start;

    @FXML
    public Button server_stop;

    @FXML
    public TextField user_name;

    @FXML
    public PasswordField password;

    @FXML
    public TextField resoureces_dir;

    @FXML
    public Text server_status;

    @FXML
    private Button add_user;

    @FXML
    private ListView<Data> server_list;

    @FXML
    private Button choose_file_dir;

    private ObservableList<Data> list = FXCollections.observableArrayList();
    private SimpleObjectProperty<Status> server_status_info = new SimpleObjectProperty<>();

    private SimpleFtpServer simpleFtpServer = null;

    @FXML
    public void initialize() {

        initStatus();
        server_list.setPlaceholder(new Label("暂无服务信息!"));
        server_list.setItems(list);
        server_list.setCellFactory(new Callback<>() {
            @Override
            public ListCell<Data> call(ListView<Data> param) {
                return new ListCell<>() {
                    @Override
                    protected void updateItem(Data data, boolean b) {
                        super.updateItem(data, b);
                        if (!b) {
                            HBox hBox = new HBox();
                            hBox.setAlignment(Pos.CENTER);
                            hBox.getChildren().add(new Label("username:" + data.username + ",password:" + data.password + ",rootDir:" + data.rootDir));
                            this.setGraphic(hBox);
                        }
                    }
                };
            }
        });
        server_list.setFixedCellSize(40);
        add_user.setOnAction(event -> {
            if (user_name.getText().length() == 0 ){
                AlertUtils.alert_warning("用户名不能为空!");
                return;
            }
            if (password.getText().length() == 0 ){
                AlertUtils.alert_warning("密码不能为空!");
                return;
            }

            if (resoureces_dir.getText().length() == 0 ){
                AlertUtils.alert_warning("资源文件夹不能为空!");
                return;
            }
            Data data = new Data();
            data.setUsername(user_name.getText());
            data.setPassword(password.getText());
            data.setRootDir(resoureces_dir.getText());

            list.add(data);

            //清楚输入框
            user_name.setText(null);
            password.setText(null);
            resoureces_dir.setText(null);
        });

        server_start.setOnAction(event -> {

            simpleFtpServer = SimpleFtpServer.create();

            for (Data item : server_list.getItems()) {
                BaseUser user = new BaseUser();
                List<Authority> list = new ArrayList<>();
                list.add(new WritePermission());
                user.setAuthorities(list);
                user.setName(item.username);
                user.setPassword(item.password);
                user.setHomeDirectory(item.rootDir);
                simpleFtpServer.addUser(user);
            }
            simpleFtpServer.start();
            startStatus();
        });

        server_stop.setOnAction(event -> {
            simpleFtpServer.stop();
            stopStatus();
        });

        choose_file_dir.setText(null);
        ImageView iv = new ImageView(new Image(ImagePath.path(ImagePath.ImagePathType.IMAGE_FILE)));
        iv.setPreserveRatio(true);
        iv.setFitWidth(18);
        choose_file_dir.setGraphic(iv);
        choose_file_dir.setOnAction(event -> {
            Stage stage = new Stage();
            DirectoryChooser dc = new DirectoryChooser();
            dc.setTitle("文件夹选择器");
            File file = dc.showDialog(stage);
            if (file == null){
               return;
            }
            resoureces_dir.setText(file.getPath());
        });
    }

    private void stopStatus(){
        server_status.setFill(Paint.valueOf("#ccffccff"));
        server_status.setText(Status.stop.desc);
        server_status_info.set(Status.stop);
    }

    private void startStatus(){
        server_status.setFill(Paint.valueOf("#ccffccff"));
        server_status.setText(Status.start.desc);
        server_status_info.set(Status.start);
    }

    private void initStatus(){
        server_status.setFill(Paint.valueOf("#ccffccff"));
        server_status.setText(Status.init.desc);
        server_status_info.set(Status.init);
    }

    public static class Data{

        private String username;
        private String password;
        private String rootDir;

        public Data() {
        }

        public Data(String username, String password, String rootDir) {
            this.username = username;
            this.password = password;
            this.rootDir = rootDir;
        }

        public String getUsername() {
            return username;
        }

        public void setUsername(String username) {
            this.username = username;
        }

        public String getPassword() {
            return password;
        }

        public void setPassword(String password) {
            this.password = password;
        }

        public String getRootDir() {
            return rootDir;
        }

        public void setRootDir(String rootDir) {
            this.rootDir = rootDir;
        }
    }
}
